<template>
  <div class="user-auth">
    <!-- 注册/登录表单 -->
    <el-card class="form-card">
      <div class="form-header">
        <img src="@/assets/logo.png" alt="Logo" class="logo" />
        <h2>{{ activeForm === 'register' ? '创建账号' : '登录' }}</h2>
        <p class="subtitle">{{ activeForm === 'register' ? '创建您的账号' : '使用您的账号登录' }}</p>
      </div>

      <!-- 注册表单 -->
      <el-form v-if="activeForm === 'register'" :model="registerForm" :rules="registerRules" ref="registerFormRef">
        <el-form-item prop="userName">
          <el-input 
            v-model="registerForm.userName" 
            placeholder="用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="email">
          <el-input 
            v-model="registerForm.email" 
            placeholder="邮箱"
            :prefix-icon="Message"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            placeholder="确认密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-button type="primary" class="submit-btn" @click="handleRegister">创建账号</el-button>
        <div class="form-footer">
          已有账号？
          <el-button link type="primary" @click="activeForm = 'login'">登录</el-button>
        </div>
      </el-form>

      <!-- 登录表单 -->
      <el-form v-if="activeForm === 'login'" :model="loginForm" :rules="loginRules" ref="loginFormRef">
        <el-form-item prop="email">
          <el-input 
            v-model="loginForm.userName"
            placeholder="用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-button type="primary" class="submit-btn" @click="handleLogin">登录</el-button>
        <div class="form-footer">
          <el-button link type="primary" @click="activeForm = 'resetPwd'">忘记密码？</el-button>
          <el-button link type="primary" @click="activeForm = 'register'">创建账号</el-button>
        </div>
      </el-form>

      <!-- 重置密码表单 -->
      <template v-if="activeForm === 'resetPwd'">
        <el-steps :active="resetPwdStep" finish-status="success" simple>
          <el-step title="验证邮箱" />
          <el-step title="验证码" />
          <el-step title="重置密码" />
        </el-steps>

        <!-- 步骤一：输入邮箱 -->
        <el-form v-if="resetPwdStep === 1" :model="resetPwdForm" :rules="resetPwdRules" ref="resetPwdFormStep1Ref">
          <el-form-item prop="email">
            <el-input 
              v-model="resetPwdForm.email" 
              placeholder="请输入您的邮箱"
              :prefix-icon="Message"
            />
          </el-form-item>
          <el-button type="primary" class="submit-btn" @click="handleResetPwdStep1">发送验证码</el-button>
        </el-form>

        <!-- 步骤二：验证码验证 -->
        <el-form v-if="resetPwdStep ===2" :model="resetPwdForm" :rules="resetPwdRules" ref="resetPwdFormStep2Ref">
          <el-form-item prop="code">
            <el-input 
              v-model="resetPwdForm.code" 
              placeholder="请输入验证码"
              :prefix-icon="Key"
            />
          </el-form-item>
          <el-button type="primary" class="submit-btn" @click="handleResetPwdStep2">验证</el-button>
        </el-form>

        <!-- 步骤三：设置新密码 -->
        <el-form v-if="resetPwdStep === 3" :model="resetPwdForm" :rules="resetPwdRules" ref="resetPwdFormStep3Ref">
          <el-form-item prop="newPassword">
            <el-input 
              v-model="resetPwdForm.newPassword" 
              type="password" 
              placeholder="新密码"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input 
              v-model="resetPwdForm.confirmPassword" 
              type="password" 
              placeholder="确认新密码"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          <el-button type="primary" class="submit-btn" @click="handleResetPwdStep3">确认修改</el-button>
        </el-form>

        <div class="form-footer" v-if="resetPwdStep === 1">
          <el-button link type="primary" @click="activeForm = 'login'">返回登录</el-button>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Key } from '@element-plus/icons-vue'
import { 
  usersRegisterService, 
  usersLoginService,
  resetPwdStep1Service,
  resetPwdStep2Service,
  resetPwdStep3Service
} from '@/api/users'

// 表单引用
const registerFormRef = ref(null)
const loginFormRef = ref(null)
const resetPwdFormStep1Ref = ref(null)
const resetPwdFormStep2Ref = ref(null)
const resetPwdFormStep3Ref = ref(null)

// 活动表单和重置密码步骤
const activeForm = ref('login')
const resetPwdStep = ref(1)

// 登录表单数据
const loginForm = reactive({
  userName: '',
  password: ''
})

// 注册表单数据
const registerForm = reactive({
  userName: '',
  password: '',
  confirmPassword: '',
  email: ''
})

// 重置密码表单数据
const resetPwdForm = reactive({
  email: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

// 验证规则
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能小于6位'))
  } else if (value.length > 20) {
    callback(new Error('密码长度不能超过20位'))
  } else {
    if (registerForm.confirmPassword !== '') {
      registerFormRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}
//注册密码两次验证
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}
//重置密码两次验证
const validateConfirmPassword1 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== resetPwdForm.confirmPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}
// 登录表单验证规则
const loginRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 注册表单验证规则
const registerRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 重置密码表单验证规则
const resetPwdRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword1, trigger: 'blur' }
  ]
}

// 通用表单验证方法
const validateForm = async (formRef) => {
  if (!formRef.value) return false
  try {
    await formRef.value.validate()
    return true
  } catch (error) {
    return false
  }
}

// 处理注册
// 处理注册部分的代码修改如下
const handleRegister = async () => {
  if (!await validateForm(registerFormRef)) {
    ElMessage.warning('请正确填写所有必填项')
    return
  }

  try {
    const registerData = {
      userName: registerForm.userName,
      password: registerForm.password,
      email: registerForm.email
    }
    
    console.log('发送的注册数据:', registerData) // 添加调试日志
    const {code,message}  = await usersRegisterService(registerData)
    console.log('注册响应:', code,message) // 添加调试日志
    
    if (code === 200) {
      ElMessage.success('注册成功')
      activeForm.value = 'login'
      // 清空表单
      registerForm.userName = ''
      registerForm.password = ''
      registerForm.confirmPassword = ''
      registerForm.email = ''
    } else {
      ElMessage.error(message || '注册失败')
    }
  } catch (error) {
    console.error('注册错误:', error) // 添加错误日志
    // ElMessage.error('注册失败，请稍后重试')
  }
}

// 处理登录
const handleLogin = async () => {
  if (!await validateForm(loginFormRef)) {
    ElMessage.warning('请正确填写所有必填项')
    return
  }

  try {
    const {code,message, data } = await usersLoginService(loginForm)

    if (code === 200) {
      ElMessage.success('登录成功')
      // TODO: 处理登录成功后的逻辑
    } else {
      console.log(data)
      ElMessage.error(message || '登录失败')
    }
  } catch (error) {
    // ElMessage.error('登录失败，请稍后重试')
  }
}

// 处理重置密码步骤一
const handleResetPwdStep1 = async () => {
  if (!await validateForm(resetPwdFormStep1Ref)) {
    ElMessage.warning('请输入正确的邮箱地址')
    return
  }

  try {
    const { message,code} = await resetPwdStep1Service(resetPwdForm.email)
    if (code === 200) {
      ElMessage.success('验证码已发送')
      resetPwdStep.value = 2
    } else {
      ElMessage.error(message|| '发送验证码失败')
    }
  } catch (error) {
    // ElMessage.error('发送验证码失败，请稍后重试')
  }
}

// 处理重置密码步骤二
const handleResetPwdStep2 = async () => {
  if (!await validateForm(resetPwdFormStep2Ref)) {
    ElMessage.warning('请输入正确的验证码')
    return
  }

  try {

    const { massage,code } = await resetPwdStep2Service({
      email: resetPwdForm.email,
      code: resetPwdForm.code
    })
    if (code === 200) {
      ElMessage.success('验证码验证成功')
      resetPwdStep.value = 3
    } else {
      ElMessage.error(massage || '验证码验证失败')
    }
  } catch (error) {
    // ElMessage.error('验证码验证失败，请稍后重试')
  }
}

// 处理重置密码步骤三
const handleResetPwdStep3 = async () => {
  if (!await validateForm(resetPwdFormStep3Ref)) {
    ElMessage.warning('请正确填写新密码')
    return
  }

  try {
    const { code,massage} = await resetPwdStep3Service(resetPwdForm.newPassword)
    if (code === 200) {
      ElMessage.success('密码重置成功')
      resetPwdStep.value = 1
      Object.assign(resetPwdForm, {
        email: '',
        code: '',
        newPassword: '',
        confirmPassword: ''
      })
      activeForm.value = 'login'
    } else {
      ElMessage.error(massage || '密码重置失败')
    }
  } catch (error) {
    // ElMessage.error('密码重置失败，请稍后重试')
  }
}
</script>

<style scoped>
.user-auth {
  max-width: 400px;
  margin: 40px auto;
  padding: 20px;
  position: relative;
  z-index: 1;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.form-card {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 30px;
  transition: transform 0.3s ease;
  cursor: default;
}

.form-card:hover {
  transform: translateY(-2px);
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
  user-select: none;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 20px;
  transition: transform 0.3s ease;
}

.logo:hover {
  transform: scale(1.05);
}

h2 {
  margin: 0;
  font-size: 24px;
  color: #202124;
  font-weight: 400;
  user-select: none;
}

.subtitle {
  margin: 10px 0 0;
  font-size: 16px;
  color: #5f6368;
  user-select: none;
}

.submit-btn {
  width: 100%;
  margin-top: 20px;
  height: 40px;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.form-footer {
  margin-top: 20px;
  text-align: center;
  color: #5f6368;
  display: flex;
  justify-content: center;
  gap: 20px;
  user-select: none;
}

:deep(.el-input__wrapper) {
  padding: 0 15px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  transition: all 0.3s ease;
  cursor: text;
}

:deep(.el-input__wrapper:hover) {
  background: rgba(255, 255, 255, 1);
}

:deep(.el-input__inner) {
  height: 40px;
}

:deep(.el-form-item__error) {
  padding-top: 4px;
  user-select: none;
}

.el-steps {
  margin: 20px 0 30px;
  user-select: none;
}

:deep(.el-button--link) {
  transition: all 0.3s ease;
}

:deep(.el-button--link:hover) {
  text-decoration: none;
  transform: translateY(-1px);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-card {
  animation: fadeIn 0.5s ease-out;
}

/* 允许输入框文本选择 */
:deep(.el-input__inner) {
  user-select: text !important;
  -webkit-user-select: text !important;
  -moz-user-select: text !important;
  -ms-user-select: text !important;
}

/* 确保按钮和链接有正确的光标 */
:deep(.el-button) {
  cursor: pointer !important;
}

/* 步骤条样式优化 */
:deep(.el-steps) {
  margin-bottom: 30px;
}

:deep(.el-step__title) {
  font-size: 14px;
  color: #5f6368;
}

:deep(.el-step__title.is-success) {
  color: #67c23a;
}

:deep(.el-step__title.is-process) {
  color: #409eff;
  font-weight: 500;
}

/* 表单项间距优化 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}
</style>